package com.dzy.boot.lock.core;

import com.dzy.boot.lock.DLockProperties;
import com.dzy.boot.lock.annotation.DLock;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;

import com.dzy.boot.lock.model.LockInfo;
import com.dzy.boot.lock.model.LockType;

public class LockInfoProvider {

    public static final String LOCK_NAME_PREFIX = "dlock";
    public static final String LOCK_NAME_SEPARATOR = ":";


    @Autowired
    private DLockProperties lockConfig;

    @Autowired
    private BusinessKeyProvider businessKeyProvider;

    public LockInfo get(ProceedingJoinPoint joinPoint, DLock dLock) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        LockType type= dLock.lockType();
        String businessKeyName=businessKeyProvider.getKeyName(joinPoint, dLock);
        String lockName = LOCK_NAME_PREFIX+LOCK_NAME_SEPARATOR+getName(dLock.name(), signature)+businessKeyName;
        long waitTime = getWaitTime(dLock);
        long leaseTime = getLeaseTime(dLock);
        return new LockInfo(type,lockName,waitTime,leaseTime);
    }

    private String getName(String annotationName, MethodSignature signature) {
        if (annotationName.isEmpty()) {
            return String.format("%s:%s", signature.getDeclaringTypeName(), signature.getMethod().getName());
        } else {
            return annotationName;
        }
    }


    private long getWaitTime(DLock lock) {
        return lock.waitTime() == Long.MIN_VALUE ?
        		lockConfig.getWaitTime() : lock.waitTime();
    }

    private long getLeaseTime(DLock lock) {
        return lock.leaseTime() == Long.MIN_VALUE ?
        		lockConfig.getLeaseTime() : lock.leaseTime();
    }
}
